function [tg_hist_new, cxt_hist_new] = update_histogram_model(im, pos, target_sz, update_rate, new_model, tg_hist)
% Update histogram model to compute color ratio feature
    [h,w,d]=size(im);
    [rm, cm] = ndgrid(1:h,1:w);
    tg_mask = 1-(rm-pos(1)).^2/(target_sz(1).^2/4)-(cm-pos(2)).^2/(target_sz(2).^2/4);
    tg_mask(find(tg_mask<=0))=0;
    im_array = reshape(double(im),h*w,d);
    bin_indices = floor(im_array/16)+1;
    cxt2_mask = ones([h,w]);
    cxt3_mask = ones([h,w]);
    cxt4_mask = ones([h,w]);
    disty = abs(rm-pos(1));
    cxt2_mask(find(disty>=target_sz(1)))=0;
    distx = abs(cm-pos(2));
    cxt2_mask(find(distx>=target_sz(2)))=0;
    cxt3_mask(find(disty>=1.5*target_sz(1)))=0;
    cxt3_mask(find(distx>=1.5*target_sz(2)))=0;
    cxt4_mask(find(disty>=2*target_sz(1)))=0;
    cxt4_mask(find(distx>=2*target_sz(2)))=0;
    
    if d==1 % If grayscale image
        if new_model
            tg_hist_new = accumarray(bin_indices, tg_mask(:), [16 1])/sum(tg_mask(:));
        else
            tg_hist_new = (1-update_rate)*tg_hist + update_rate*accumarray(bin_indices, tg_mask(:), [16 1])/sum(tg_mask(:));
        end
        cxt2_hist = accumarray(bin_indices, cxt2_mask(:), [16 1])/sum(cxt2_mask(:));
        cxt3_hist = accumarray(bin_indices, cxt3_mask(:), [16 1])/sum(cxt3_mask(:));
        cxt4_hist = accumarray(bin_indices, cxt4_mask(:), [16 1])/sum(cxt4_mask(:));
        cxt_hist_new = {cxt2_hist, cxt3_hist, cxt4_hist};
    else
        if new_model
            tg_hist_new = accumarray(bin_indices, tg_mask(:), [16 16 16])/sum(tg_mask(:));
        else
            tg_hist_new = (1-update_rate)*tg_hist + update_rate*accumarray(bin_indices, tg_mask(:), [16 16 16])/sum(tg_mask(:));
        end
        cxt2_hist = accumarray(bin_indices, cxt2_mask(:), [16 16 16])/sum(cxt2_mask(:));
        cxt3_hist = accumarray(bin_indices, cxt3_mask(:), [16 16 16])/sum(cxt3_mask(:));
        cxt4_hist = accumarray(bin_indices, cxt4_mask(:), [16 16 16])/sum(cxt4_mask(:));
        cxt_hist_new = {cxt2_hist, cxt3_hist, cxt4_hist};
    end
end

